package com.kaibes.im.utils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;

public class BitmapUtil {

    public static Bitmap toRoundBitmap(Bitmap bitmap) {
	int width = bitmap.getWidth();
	int height = bitmap.getHeight();

	int r = 0;

	if (width > height) {
	    r = height;
	} else {
	    r = width;
	}

	Bitmap photoGroundBitmap = Bitmap.createBitmap(width, height,
		Config.ARGB_8888);
	Canvas canvas = new Canvas(photoGroundBitmap);
	Paint paint = new Paint();
	paint.setAntiAlias(true);
	RectF rect = new RectF(0, 0, r, r);
	canvas.drawRoundRect(rect, r / 2, r / 2, paint);
	// 设置当两个图形相交时的模式，SRC_IN为取SRC图形相交的部分，多余的将被去掉
	paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	canvas.drawBitmap(bitmap, null, rect, paint);
	return photoGroundBitmap;
    }

    public static Bitmap toRoundBitmapGray(Bitmap bitmap) {

	int width = bitmap.getWidth();
	int height = bitmap.getHeight();

	// Bitmap.Config.ARGB_8888这时候可以把透明度表现出来，实际上圆形图片只是非园部分透明化，所以这里不能用RGB_565
	Bitmap photoGroundBitmap = Bitmap.createBitmap(width, height,
		Bitmap.Config.ARGB_8888);
	Canvas canvas = new Canvas(photoGroundBitmap);
	Paint paint = new Paint();
	paint.setAntiAlias(true);
	// paint.setAlpha(255);

	int r = 0;
	if (width > height) {
	    r = height;
	} else {
	    r = width;
	}
	RectF rect = new RectF(0, 0, r, r);
	canvas.drawRoundRect(rect, r / 2, r / 2, paint);

	// 颜色矩阵
	ColorMatrix cm = new ColorMatrix();
	// 设为灰色
	cm.setSaturation(0);
	// 设置颜色过滤器
	paint.setColorFilter(new ColorMatrixColorFilter(cm));

	// 设置当两个图形相交时的模式，SRC_IN为取SRC图形相交的部分，多余的将被去掉
	paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	// canvas.drawBitmap(bitmap, null, rect, paint);
	canvas.drawBitmap(bitmap, 0, 0, paint);

	return photoGroundBitmap;
    }

    public static Bitmap toGrayscale(Bitmap bitmap) {
	int height = bitmap.getHeight();
	int width = bitmap.getWidth();

	Bitmap bmpGrayscale = Bitmap.createBitmap(width, height,
		Bitmap.Config.ARGB_8888);

	Paint paint = new Paint();
	ColorMatrix cm = new ColorMatrix();
	cm.setSaturation(0);
	paint.setColorFilter(new ColorMatrixColorFilter(cm));

	Canvas canvas = new Canvas(bmpGrayscale);
	canvas.drawBitmap(bitmap, 0, 0, paint);

	return bmpGrayscale;
    }

}
